package cn.botter.auth.application.controller;

/**
 * @BelongsProject: bo-club
 * @BelongsPackage: cn.botter.application.controller
 * @Author: 爱写Bug的Botter
 * @CreateTime: 2025-03-13:17:30
 * @Description: 描述
 * @Version: 1.0
 */

import cn.botter.auth.application.convert.AuthUserConvert;
import cn.botter.auth.application.exception.RegistrationException;
import cn.botter.auth.domain.entity.AuthUserBO;
import cn.botter.auth.domain.service.AuthUserDomainService;
import cn.botter.auth.entity.AuthUserDTO;
import cn.botter.auth.entity.Result;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.regex.Pattern;

/**
 * 登录测试
 */
@RestController
@RequestMapping("/user/")
@Slf4j
@Validated
public class AuthUserController {
     // 邮箱正则：匹配常见邮箱格式（如 user@domain.com）
     private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
     // 大陆手机号正则：以1开头，第二位3-9，共11位数字
     private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

     @Resource
     private AuthUserDomainService authUserDomainService;

     /**
      * 用户注册
      */
     @RequestMapping("register")
     public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
          try {
               checkVaild(authUserDTO);
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.add.dto:{}", JSON.toJSONString(authUserDTO));
               }

               AuthUserBO authUserBO = AuthUserConvert.INSTANCE.convertDtoToBO(authUserDTO);
               /**
                * 先查询一下数据库是否存在该用户
                */
               
               Integer register = authUserDomainService.register(authUserBO);
               if (register != null && register > 0)
                    return Result.OK("注册成功",true );
               else{
                    throw new RegistrationException("用户已存在");
               }
          } catch (Exception e) {
               log.info("AuthUserController.add.error:{}", e.getMessage());
               return Result.FAILED("注册失败",e.getMessage());
          }

     }

     /**
      * 更新用户
      */
     @RequestMapping("update")
     public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
          try {
//               Preconditions.checkNotNull(authUserDTO.getId() , "用户id不能为空");
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.update.dto:{}", JSON.toJSONString(authUserDTO));
               }

               AuthUserBO authUserBO = AuthUserConvert.INSTANCE.convertDtoToBO(authUserDTO);
               Boolean updated = authUserDomainService.update(authUserBO);
               if (updated != null && updated){
                    return Result.OK("更新用户信息成功!", updated);
               }
               else {
                    throw new RegistrationException("更新用户数为0,数据库不存在"+authUserDTO.getUserName()+"的用户!!!");
               }
          } catch (Exception e) {
               log.info("AuthUserController.update.error:{}", e.getMessage());
               return Result.FAILED("更新用户信息失败!",e.getMessage());
          }
     }

     /**
      * 删除用户
      */
     @RequestMapping("delete")
     public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
          try {
               Preconditions.checkNotNull(authUserDTO.getId() , "用户id不能为空");
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.delete.dto:{}", JSON.toJSONString(authUserDTO));
               }

               AuthUserBO authUserBO = AuthUserConvert.INSTANCE.convertDtoToBO(authUserDTO);
               Boolean delete = authUserDomainService.delete(authUserBO);
               if (delete != null && delete){
                    return Result.OK("删除用户成功!", delete);
               }
               else {
                    throw new RegistrationException("用户不存在");
               }
          } catch (Exception e) {
               log.info("AuthUserController.delete.error:{}", e.getMessage());
               return Result.FAILED("删除用户失败!",e.getMessage());
          }
     }

     /**
      * 更改用户状态
      */
     @RequestMapping("changeStatus")
     public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
          try {
               Preconditions.checkNotNull(authUserDTO.getId() , "用户id不能为空");
               Preconditions.checkNotNull(authUserDTO.getStatus() , "用户状态不能为空");
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
               }
               AuthUserBO authUserBO = AuthUserConvert.INSTANCE.convertDtoToBO(authUserDTO);
               Boolean update = authUserDomainService.update(authUserBO);
               if (update!=null && update){
                    return Result.OK("修改用户状态成功!", update);
               }
               else {
                    throw new RegistrationException("用户不存在");
               }
          } catch (Exception e) {
               log.info("AuthUserController.changeStatus.error:{}", e.getMessage());
               return Result.FAILED("修改用户状态失败!",e.getMessage());
          }
     }

     /**
      * 查询用户信息
      */
     @RequestMapping("getUserInfo")
     public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
          try {
               Preconditions.checkNotNull(authUserDTO.getUserName() , "用户名不能为空");
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDTO));
               }
               AuthUserBO authUserBO = AuthUserConvert.INSTANCE.convertDtoToBO(authUserDTO);
               AuthUserBO getUserBO = authUserDomainService.getUserInfo(authUserBO);
               AuthUserDTO result = AuthUserConvert.INSTANCE.convertBoToDto(getUserBO);
               if (result!=null){
                    return Result.OK("查询用户信息成功!", result);
               }
               else {
                    throw new RegistrationException("查询用户信息失败");
               }
          } catch (Exception e) {
               log.info("AuthUserController.getUserInfo.error:{}", e.getMessage());
               return Result.FAILED("查询用户信息失败!",e.getMessage());
          }
     }





     private static void checkVaild(AuthUserDTO authUserDTO) {
          // 用户名校验：非空
          Preconditions.checkArgument(
                  !StringUtils.isEmpty(authUserDTO.getUserName()),
                  "用户名不能为空"
          );
          // 昵称校验：非空
          Preconditions.checkArgument(
                  !StringUtils.isEmpty(authUserDTO.getNickName()),
                  "用户昵称不能为空"
          );
          // 密码校验：非 null 且非空字符串
          Preconditions.checkArgument(
                  authUserDTO.getPassword() != null && !authUserDTO.getPassword().trim().isEmpty(),
                  "用户密码不能为空"
          );
          // 邮箱格式校验
          Preconditions.checkArgument(
                  EMAIL_PATTERN.matcher(authUserDTO.getEmail()).matches(),
                  "邮箱格式不正确"
          );
          // 大陆手机号格式校验
          Preconditions.checkArgument(
                  PHONE_PATTERN.matcher(authUserDTO.getPhone()).matches(),
                  "手机号格式不正确"
          );
     }


     // 测试登录  ---- http://localhost:8081/acc/doLogin?name=zhang&pwd=123456
     @RequestMapping("doLogin")
     public SaResult doLogin(@RequestParam("validCode")String validCode) {
          Preconditions.checkArgument(!StringUtils.isEmpty(validCode) , "验证码不能为空！");
          // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
          SaTokenInfo saTokenInfo = authUserDomainService.doLogin(validCode);

          if (saTokenInfo != null){
               return SaResult.data(saTokenInfo);
          }

          return SaResult.error("注册失败！");
     }
     // 查询登录状态  ---- http://localhost:8081/acc/isLogin
     @RequestMapping("isLogin")
     public SaResult isLogin() {
     //        System.out.println(StpUtil.getTokenTimeout(StpUtil.getTokenInfo().getTokenValue()));
          return SaResult.data("用户是否登录:"+StpUtil.getTokenInfo().isLogin);
     }

     // 查询 Token 信息  ---- http://localhost:8081/acc/tokenInfo
     @RequestMapping("tokenInfo")
     public SaResult tokenInfo() {
          return SaResult.data(StpUtil.getTokenInfo());
     }

     // 测试注销  ---- http://localhost:8081/acc/logout
     @RequestMapping("logOut")
     public Result logout(@RequestParam String userName) {
          try{
               if (log.isInfoEnabled()){
                    log.info("AuthUserController.logOut.username:{}", userName);
               }
               StpUtil.logout(userName);
               return Result.OK();
          }
          catch (Exception e){
               log.info("AuthUserController.logOut.error:{}", e.getMessage(),e);
               return Result.FAILED();
          }
     }



}
